package com.xxgc.helloword.service.impl;

import com.xxgc.helloword.bean.Users;
import com.xxgc.helloword.bean.UsersExample;
import com.xxgc.helloword.dao.UsersMapper;
import com.xxgc.helloword.po.Info;
import com.xxgc.helloword.service.ILoginService;
import com.xxgc.helloword.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;

@Service
public class LoginService implements ILoginService {
    //业务逻辑层和dao层关联
    @Autowired
    private UsersMapper um;

    @Override
    public Info namePassLogin(Users u) {
        UsersExample example = new UsersExample();
        example.createCriteria()
                .andUsernameEqualTo(u.getUsername())
                .andPasswordEqualTo(u.getPassword());
        //alt+shif+l  ctrl+alt+v 生成返回结果
        List<Users> users = um.selectByExample(example);
        //判断是否为空
        if(CollectionUtils.isEmpty(users)) {
            return new Info(-200,"用户名或密码错误！登录失败");
        }else {
            Users user = users.get(0);
            //把密码去掉
            user.setPassword(null);
            Info info = new Info(200, "登录成功！", user);
            HashMap<String, String> tokenMap = new HashMap<>();
            //要把加密的对象放到map中
            tokenMap.put("id",String.valueOf(user.getId()));
            //利用工具类加密得到token
            String token = JWTUtils.getToken(tokenMap);
            info.setToken(token);
            return info;
        }
    }
}
